<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品编码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="更新时间" prop="lastUpdateTime">
        <el-date-picker
          clearable
          v-model="queryParams.lastUpdateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="数量" prop="quantityCount">
        <el-input
          v-model="queryParams.quantityCount"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="方案编码" prop="strategyCode">
        <el-input
          v-model="queryParams.strategyCode"
          placeholder="请输入方案编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="留仓原因" prop="abnomalReason">
        <el-input
          v-model="queryParams.abnomalReason"
          placeholder="请输入留仓原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购单号" prop="purchaseOrderNumber">
        <el-input
          v-model="queryParams.purchaseOrderNumber"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购单号" prop="purchaseOrderNumber">
        <el-select
          v-model="queryParams.allocationStatus"
          placeholder="分配状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_allocation_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
          <!-- <el-option label="分配成功" value="allocateSuccess" />
          <el-option label="分配失败" value="allocateFailure" /> -->

          <!-- <el-option label="待生成" value="toAllocate" />
          <el-option label="已生成" value="isAllocated" /> -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['productAllocation:alnomalRestock:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['productAllocation:alnomalRestock:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['productAllocation:alnomalRestock:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['productAllocation:alnomalRestock:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="opentagkey"
          >留仓分配</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="alnomalRestockList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="分配状态" align="center" prop="allocationStatus">
        <template slot-scope="scope">
          <span
            v-if="scope.row.allocationStatus == 'isAllocated'"
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="handleAlnomalid(scope.row)"
          >
            <dict-tag
              :options="dict.type.sys_allocation_status"
              :value="scope.row.allocationStatus"
            />
          </span>
          <span v-else>
            <dict-tag
              :options="dict.type.sys_allocation_status"
              :value="scope.row.allocationStatus"
            />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="productCode" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="lastUpdateTime"
        width="180"
      >
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantityCount" />
      <el-table-column label="方案编码" align="center" prop="strategyCode">
        <template slot-scope="scope">
          <span
            style="
              color: rgb(37, 137, 255);
              cursor: pointer;
              text-decoration: underline;
              font-weight: bold;
            "
            @click="selectformisNew(scope.row)"
          >
            {{ scope.row.strategyCode }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="留仓原因" align="center" prop="abnomalReason" />
      <el-table-column
        label="采购单号"
        align="center"
        prop="purchaseOrderNumber"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['productAllocation:alnomalRestock:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['productAllocation:alnomalRestock:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购分配异常数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="分配状态" prop="allocationStatus">
          <el-select
            v-model="form.allocationStatus"
            placeholder="分配状态"
            clearable
          >
            <!-- <el-option label="分配成功" value="allocateSuccess" />
          <el-option label="分配失败" value="allocateFailure" /> -->
            <el-option
              v-for="dict in dict.type.sys_allocation_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="更新时间" prop="lastUpdateTime">
          <el-date-picker
            clearable
            v-model="form.lastUpdateTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数量" prop="quantityCount">
          <el-input v-model="form.quantityCount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="方案编码" prop="strategyCode">
          <el-input v-model="form.strategyCode" placeholder="请输入方案编码" />
        </el-form-item>
        <el-form-item label="留仓原因" prop="abnomalReason">
          <el-input v-model="form.abnomalReason" placeholder="请输入留仓原因" />
        </el-form-item>
        <el-form-item label="采购单号" prop="purchaseOrderNumber">
          <el-input
            v-model="form.purchaseOrderNumber"
            placeholder="请输入采购单号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="tagkeyVisible"
      width="600px"
      append-to-body
      v-if="tagkeyVisible"
    >
      <el-card style="margin-bottom: 16px">
        <div slot="header">
          异常分配
          <!-- <span
            >采购单号:{{ this.list[0].purchaseOrderNumber }},sku:{{
              this.list[0].sku
            }}</span
          > -->
        </div>
        <div class="el-dialog-div">
          <el-form :model="formData" :inline="true">
            <el-form-item label="采购单号:">
              {{ this.list[0].purchaseOrderNumber }}
            </el-form-item>
            <el-form-item label="sku:">
              {{ this.list[0].productCode }}
            </el-form-item>
            <el-row>
              <el-form-item label="方案编码">
                {{ this.list[0].strategyCode }}
                <!-- <el-input v-model="strategyCode" placeholder="请输入方案编码" /> -->
              </el-form-item>
              <!-- <el-button
                type="primary"
                plain
                size="mini"
                @click="openCode = true"
              >
                +
              </el-button> -->
            </el-row>
            <el-row>
              <el-form-item label="数量">
                {{ this.list[0].quantityCount }}
                <!-- <el-input v-model="strategyCode" placeholder="请输入方案编码" /> -->
              </el-form-item>
              <!-- <el-button
                type="primary"
                plain
                size="mini"
                @click="openCode = true"
              >
                +
              </el-button> -->
            </el-row>
            <el-row>
              <el-form-item
                style="width: 200px"
                label="店铺名称"
              ></el-form-item>
              <el-form-item
                style="width: 100px"
                label="计划分配数量"
              ></el-form-item>
            </el-row>
            <el-form-item
              v-for="(item, index) in formData.libraryIdList"
              :key="index"
            >
              <!-- <el-input
              style="width: 150px"
              v-model="item.storeName"
              placeholder="店铺名称"
            ></el-input> -->
              <el-select
                v-model="item.storeName"
                clearable
                filterable
                placeholder="店铺"
                style="width: 200px"
              >
                <el-option
                  v-for="item in ShopInfoList"
                  :key="item.comment"
                  :label="`${item.comment}`"
                  :value="item.comment"
                >
                </el-option>
              </el-select>
              <!-- <el-input
              style="width: 150px"
              v-model="item.field_name"
              placeholder="请输入字段值"
            ></el-input> -->
              <el-input
                style="width: 150px"
                v-model="item.plannedAllocationQty"
                placeholder="计划分配数量"
              ></el-input>

              <span
                v-if="formData.libraryIdList.length > 0"
                style="margin-left: 5px"
              >
                <el-button type="primary" size="mini" @click="addLibraryIdList"
                  >新增</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="delRow(item, index)"
                  >删除</el-button
                >
              </span>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitformData">确 定</el-button>
        <el-button @click="canceltagkeyVisible">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="openInfo"
      width="1500px"
      append-to-body
      v-if="openInfo"
    >
      <div class="el-dialog-div">
        <component :is="'detail'" :Alnomalid="Alnomalid"></component>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="openstrategyCode"
      width="1500px"
      append-to-body
      v-if="openstrategyCode"
    >
      <div class="el-dialog-div">
        <component :is="'strategy'" :strategyCode="strategyCode"></component>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAlnomalRestock,
  getAlnomalRestock,
  delAlnomalRestock,
  addAlnomalRestock,
  updateAlnomalRestock,
} from "@/api/productAllocation/alnomalRestock";
import {
  selectlist,
  getTrigger,
  delTrigger,
  addTrigger,
  updateTrigger,
  syncTriggerTables,
  processandinsert,
  numbers,
} from "@/api/productAllocation/trigger";
import { JstShopInfo } from "@/api/conf/BiStoreWarehouseBinding";

import strategy from "@/views/productAllocation/strategy/index.vue";
import detail from "@/views/productAllocation/detail/index.vue";
export default {
  name: "AlnomalRestock",
  dicts: ["sys_allocation_status"],

  components: { detail, strategy },
  props: {
    taskId: {
      type: String,
      default: () => {},
    },
    row: {
      type: Object,
      default: () => {},
    },
    rowAlnomal: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      strategyCode: null,
      openstrategyCode: false,
      Alnomalid: null,
      openInfo: false,
      tagkeyVisible: false,
      formData: {
        libraryIdList: [{ storeName: "", plannedAllocationQty: "" }],
      },

      ShopInfoList: [],

      list: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购分配异常数据表格数据
      alnomalRestockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        allocationStatus: null,
        productCode: null,
        lastUpdateTime: null,
        quantityCount: null,
        strategyCode: null,
        abnomalReason: null,
        purchaseOrderNumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    JstShopInfo({ pageNum: 1, pageSize: 100 }).then((response) => {
      this.ShopInfoList = response.rows.map((item) => ({
        columnName: item.shopId,
        comment: item.shopName,
      }));
    });
  },
  watch: {
    taskId: {
      handler: function (newnew, oldold) {
        // this.getautoSelectProTypeList();
        this.queryParams.id = this.taskId;
        this.getList();
      },
      deep: true,
      immediate: true,
    },
    row: {
      handler: function (newnew, oldold) {
        // this.getautoSelectProTypeList();
        this.queryParams.productCode = this.row.sku;
        this.queryParams.purchaseOrderNumber = this.row.purchaseOrderNumber;
        this.getList();
      },
      deep: true,
      immediate: true,
    },
    rowAlnomal: {
      handler: function (newnew, oldold) {
        // this.getautoSelectProTypeList();
        // this.queryParams.productCode = this.rowAlnomal.sku;
        this.queryParams.purchaseOrderNumber =
          this.rowAlnomal.purchaseOrderNumber;
        this.getList();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    selectformisNew(row) {
      this.strategyCode = row.strategyCode;

      this.openstrategyCode = true;
    },
    handleAlnomalid(row) {
      this.Alnomalid = row.id;
      this.openInfo = true;
    },
    submitformData() {
      if (!this.formData.libraryIdList[0].storeName) {
        this.$modal.msgError("至少输入一个店铺");
        return;
      }
      if (!this.formData.libraryIdList[0].plannedAllocationQty) {
        this.$modal.msgError("请设置计划分配数量");
        return;
      }
      // let obj = {
      //   strategyCode: this.row.strategyCode,
      //   businessType: "priority",
      //   allocationPurchaseConfShopList: this.formData.libraryIdList,
      // };
      this.formData.libraryIdList.forEach((item) => {
        item.purchaseOrderNumber = this.list[0].purchaseOrderNumber;
        item.productCode = this.list[0].productCode;
        item.taskId = this.list[0].id;
        item.dataStatus = "abnormal";
        item.strategyCode = this.list[0].strategyCode;
      });
      console.log(JSON.stringify(this.formData.libraryIdList));
      const totalPlannedAllocationQty = this.formData.libraryIdList.reduce(
        (sum, item) => {
          // 由于plannedAllocationQty是字符串，我们需要将其转换为数字进行加法运算
          return sum + Number(item.plannedAllocationQty);
        },
        0
      ); // 第二个参数是reduce的初始值，这里设置为0
      if (totalPlannedAllocationQty != this.list[0].quantityCount) {
        this.$modal.msgError("当前分配数量不等于总数");
        return;
      }
      processandinsert(this.formData.libraryIdList).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess(response.msg);
          this.tagkeyVisible = false;
          this.getList();
          this.formData.libraryIdList = [
            { storeName: "", plannedAllocationQty: "" },
          ];
        }
        // else {
        //     this.$modal.msgError("设置失败");
        //     this.tagkeyVisible = false;
        //   }
      });
    },
    opentagkey() {
      // listShop({
      //   strategyCode: this.row.strategyCode,
      //   businessType: "priority",
      // }).then((response) => {
      //   let list = [{ storeName: "", plannedAllocationQty: "" }];
      //   if (response.rows.length > 0) {
      //     list = [];
      //     response.rows.forEach((item) => {
      //       list.push({
      //         storeName: item.storeName,
      //         plannedAllocationQty: item.plannedAllocationQty,
      //       });
      //     });
      //   }
      //   // this.cols
      //   this.formData.libraryIdList = list;
      // });
      if (this.list.length != 1) {
        this.$modal.msgError("只勾选一条记录");
        return;
      }
      if (this.list[0].allocationStatus == "isAllocated") {
        this.$modal.msgError("该条数据已分配");
        return;
      }

      this.tagkeyVisible = true;
    },
    // 取消按钮
    canceltagkeyVisible() {
      this.tagkeyVisible = false;
    },
    //添加库存名称
    addLibraryIdList() {
      this.formData.libraryIdList.push({
        storeName: "",
        plannedAllocationQty: "",
      });
    },
    //库存名称删除
    delRow(item, index) {
      if (this.formData.libraryIdList.length > 0) {
        this.formData.libraryIdList.splice(index, 1);
      } else {
        this.$message.warning("至少选择一项");
      }
    },
    /** 查询采购分配异常数据列表 */
    getList() {
      this.loading = true;
      listAlnomalRestock(this.queryParams).then((response) => {
        this.alnomalRestockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        allocationStatus: null,
        productCode: null,
        lastUpdateTime: null,
        quantityCount: null,
        strategyCode: null,
        abnomalReason: null,
        purchaseOrderNumber: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.list = selection.map((item) => item);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购分配异常数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAlnomalRestock(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购分配异常数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAlnomalRestock(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlnomalRestock(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除采购分配异常数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAlnomalRestock(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "productAllocation/alnomalRestock/export",
        {
          ...this.queryParams,
        },
        `alnomalRestock_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
